package edu.xhu.video.controller;

import edu.xhu.model.biliuser.dtos.LoginAndRegisterDto;
import edu.xhu.model.common.dtos.ResponseResult;
import edu.xhu.model.video.dtos.BiliVideoUploadDto;
import edu.xhu.video.service.BiliUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Api(value = "网页端投稿Controller层", tags = "网页端投稿Controller层")
@CrossOrigin
@RestController
@RequiredArgsConstructor
@RequestMapping("/bilivideo")
public class BiliUploadController {
    private final BiliUploadService biliUploadService;

    /**
     * 查询当前视频准备要上传的分片序号
     *
     * @param hash 视频的hash值
     * @return
     */
    @GetMapping("/ask-chunk")
    @ApiOperation("bili用户投稿")
    public ResponseResult<?> askChunk(@RequestParam("hash") String hash) {
        return biliUploadService.askCurrentChunk(hash);
    }

    /**
     * 上传分片
     *
     * @param chunk 分片的blob文件
     * @param hash  视频的hash值
     * @param index 当前分片的序号
     * @return
     * @throws IOException
     */
    @PostMapping("/upload-chunk")
    public ResponseResult<?> uploadChunk(@RequestParam("chunk") MultipartFile chunk,
                                         @RequestParam("hash") String hash,
                                         @RequestParam("index") Integer index) throws IOException {
        try {
            return biliUploadService.uploadChunk(chunk, hash, index);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(500, "分片上传失败");
        }
    }

    /**
     * 取消上传
     *
     * @param hash 视频的hash值
     * @return
     */
    @GetMapping("cancel-upload")
    public ResponseResult<?> cancelUpload(@RequestParam("hash") String hash) {
        return biliUploadService.cancelUpload(hash);
    }

    /**
     * 添加视频投稿
     *
     * @param biliVideoUploadDto 投稿数据dto
     * @return 响应对象
     */
    @PostMapping("/add")
    public ResponseResult<?> addVideo(@ModelAttribute BiliVideoUploadDto biliVideoUploadDto) {
        return biliUploadService.addVideo(biliVideoUploadDto);
    }
}
